import { Http, HTTP_PROVIDERS } from 'angular2/http';
import { Injector } from 'angular2/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';
import { AbstractControl } from "@angular/forms";
/**
 * Created by yxin on 1/2/2017.
 */

function checkUser(control: AbstractControl, source: string): Observable<any> {

  // Manually inject Http
  let injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
  let http = injector.get(Http);

  // Return an observable with null if the
  // username or email doesn't yet exist, or
  // an objet with the rejetion reason if they do
  return new Observable((obs: any) => {
    control
      .valueChanges
      .debounceTime(400)
      .flatMap(value => http.post('test', JSON.stringify({[source]: value})))
      .subscribe(
        data => {
          obs.next(null);
          obs.complete();
        },
        error => {
          let message = error.json().message;
          let reason;
          if (message === 'Username taken') {
            reason = 'usernameTaken';
          }
          if (message === 'Email taken') {
            reason = 'emailTaken';
          }
          obs.next({[reason]: true});
          obs.complete();
        }
      );
  });
}

export class UsernameEmailValidator {

  constructor() {
  }

  static checkUsername(control: AbstractControl) {
    return checkUser(control, 'username');
  }

  static checkEmail(control: AbstractControl) {
    return checkUser(control, 'email');
  }
}
